import React, { useState, useEffect, useMemo, useRef } from "react";
import * as echarts from "echarts";
export default () => {
  const ref = useRef();
  const [chart, setChart] = useState(null);
  const [data, setData] = useState(null);
  const option = useMemo(() => {
    if (!data) return null;
    let data1 = data.map((e) => e.male);
    let data2 = data.map((e) => e.female);
    let xAxisData = ["0-19岁", "20-29岁", "30-39岁", "40-100岁"];
    let emphasisStyle = {
      itemStyle: {
        shadowBlur: 10,
        shadowColor: "rgba(0,0,0,0.3)",
      },
    };
    let op = {
      grid: {
        top: "3%",
        left: "3%",
        right: "8%",
        bottom: "3%",
        containLabel: true,
      },
      color: ["#3385FF", "#F58586"],
      tooltip: {
        trigger: "axis",
        axisPointer: {
          type: "shadow",
        },
      },
      xAxis: {
        data: xAxisData,
        // name: "X Axis",
        axisLine: { onZero: true, show: false },
        splitLine: { show: false },
        splitArea: { show: false },
        axisTick: { show: false },

      },
      yAxis: {
        splitLine: {
          lineStyle: {
            type: "dashed",
          },
        },
        axisLine: {
          show: false,
        },
        axisTick: {
          show: false,
        },
      },

      series: [
        {
          name: "男性",
          type: "bar",
          stack: "one",
          emphasis: emphasisStyle,
          data: data1,
        },
        {
          name: "女性",
          type: "bar",
          stack: "one",
          emphasis: emphasisStyle,
          data: data2,
        },

      ],
    };
    return op;
  }, [data]);

  /*=======请求数据 =======*/
  const getData = () => {
    let lst = [];
    for (let i = 0; i < 4; i++) {
      lst.push({ male: Math.round(Math.random() * 1000), female: Math.round(Math.random() * 1000) });
    }
    setData(lst);
  };

  /* ======== 定时改变data ======= */
  useEffect(() => {
    getData();
    let timer = setInterval(() => {
      getData();
    }, 3000);
    return () => {
      clearInterval(timer);
    };
  }, []);

  /* ======== 生成图表实例 ======= */
  useEffect(() => {
    ref.current && setChart(echarts.init(ref.current));
  }, []);

  /* ======= 渲染图表 ====== */
  useEffect(() => {
    chart && option && chart.setOption(option);
  }, [chart, option]);

  return (
    <div style={{ width: "100%", height: "100%" }} ref={ref}></div>
  );
};
